###--------------------------------------------------------------------###
#
# R Codes for the practicals of "Fundamentals in Ecology"
#
# Bachelor 2 SIE - Sciences et Ingenierie de l'Environnement
# Ecole polytechnique federale de Lausanne (EPFL)
#
# by Eugenie Mas, Christoph Bachofen, Hannes Peter, Jade Brandani, Jonas Paccolat

###--------------------------------------------------------------------###
### Plotting with R. Part I: Basic plotting
###--------------------------------------------------------------------###
### I will first present you the basic plots, that is the most traditional and old fashion way to do plots
### In this part, every plots that I will present could be make prettier with a lot of argument such changing the colors, name, adding labels , symbols etc
### but to go faster I will only present the basic way to do it and I invite you to check the function information with ?plot for further information on how to make it prettier
### Latter I will present you the package "ggplot2" that allows to draw a lot of pretty plot very quickly 
### and is the best packages to have a quick visualization of your dataset and see the tendencies

###--------------------------------------------------###
### 1. Scatterplot -------------------------------------

plot(iris$Petal.Length)
plot(iris$Petal.Length, iris$Sepal.Length) #plot x= petal length in function of y= sepal length
plot(iris) #plot everything column of the dataset between each other

###--------------------------------------------------###
### 2. Histogram ---------------------------------------

hist(iris$Petal.Length) #ask only one argument because it represents the distribution of one numeric variable

# extract data from the plot
hist(iris$Petal.Length, plot=FALSE)
x <- hist(iris$Petal.Length, plot=F)$density

###--------------------------------------------------###
### 3. Boxplot -----------------------------------------
### use boxplot when you want to present a continuous variable in function of a factor as Country or Species
boxplot(Petal.Length ~ Species, data=iris) #you can write: boxplot(y~x) or boxplot(x,y)

#extract data from the plot
boxplot(Petal.Length ~ Species, data=iris, plot=F)
aggregate(Petal.Length ~ Species, data=iris, FUN=quantile) #extract the quantile

###--------------------------------------------------###
### 4. Barplot -----------------------------------------

# first: aggregate your data to calculate the mean of your numeric variable
iris.agg <- aggregate(Sepal.Length ~ Species, data=iris, mean)

# basic plot
barplot(iris.agg$Sepal.Length)

# use arrows as error bars in barplots
# first, create a dataframe of standard errors
iris.agg.sd <- aggregate(Sepal.Length ~ Species, data=iris, sd)

bp<-barplot(iris.agg$Sepal.Length)

arrows(bp, iris.agg$Sepal.Length + iris.agg.sd$Sepal.Length, bp, iris.agg$Sepal.Length - iris.agg.sd$Sepal.Length)

###--------------------------------------------------###
### 5. Make multiple plots in one ----------------------

# multiple plots with "par mfrow"
par(mfrow=c(2,1))#share the window of the plot between c(row,column)

# first plot
plot(iris$Petal.Length, iris$Sepal.Length)
# second plot
plot(iris$Sepal.Length, iris$Sepal.Length)

###--------------------------------------------------###
### 6. Exporting plots ---------------------------------

# exporting with the R-studio interface: go in Plots window and click on "Export"=> "Save as PDF..."

# exporting with functions
# first: check where the file will be exported to: 
getwd()
pdf("iris-plot.pdf", height=4, width=6) #open a pdf file empty
plot(iris$Sepal.Length, iris$Sepal.Length) #save the plot into the pdf
dev.off()#save the pdf into the folder

# note: 
# alternatively you can export as: jpg, png, bmp, tiff
# BUT: don't use these (because they're raster graphics, meant for photos, etc.)


###--------------------------------------------------------------------###
### Plotting with R. Part II: library "ggplot2"
###--------------------------------------------------------------------###


###--------------------------------------------------###
### 1. Install and load the package -------------------------------------
# to use a package on R, it is important to load the package on R everytime you start R
install.packages("ggplot2")
library(ggplot2)

###--------------------------------------------------###
### 2. Plotting with ggplot2 -------------------------------------

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) #you create an empty space

#add the type of plot you want with a "+"
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width))+ 
  geom_point()  #scatterplot

ggplot(iris, aes(x=Species, y=Sepal.Length))+
  geom_boxplot() #boxplot (x as to be a factor)

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width))+
  geom_line()  #scatterplot with line (quite ugly, don't use it!)

ggplot(iris, aes(x=Sepal.Length))+
  geom_histogram() #histogram (write only the x variable because you look at its distribution)

###--------------------------------------------------###
### 3. Scatterplot -------------------------------------
#the basic code
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width))+
  geom_point()

#change the size and shape of your points in a scatterplot

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width))+
  geom_point(size=2, shape=17) #the size and shape change for all the points, a number correspond to one kind of shape, you can find on internet the list of shape available on R

#change color and shape in function of a variable, here for example the species
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species, shape=Species))+ 
  geom_point()

#choose your colors and shape manually
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species, shape=Species))+
  geom_point(size=2)+
  scale_shape_manual(values=c(18, 16, 17))+ 
  scale_color_manual(values=c("darkorange","darkcyan", "goldenrod3")) #the name of the color has to be write between apostrophe ""

#change axis scale
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species, shape=Species))+
  geom_point(size=2)+
  scale_shape_manual(values=c(18, 16, 17))+ 
  scale_color_manual(values=c("darkorange","darkcyan", "goldenrod3"))+
  xlim(5, 8)+ #limit of the x axis from 5 to 8
  ylim(1.5, 5) #limit of the y axis from 1.5 to 5

#or use the function "scale_x_continuous" to change the name of the axis at the same time than the scale
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species, shape=Species))+
  geom_point(size=2)+
  scale_shape_manual(values=c(18, 16, 17))+ 
  scale_color_manual(values=c("darkorange","darkcyan", "goldenrod3"))+
  scale_x_continuous(name="Length of sepal (cm)", limits=c(5,8)) +
  scale_y_continuous(name="Width of sepal (cm)", limits=c(1.5,5))

#add horizontal and vertical lines
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species, shape=Species))+
  geom_point(size=2)+
  scale_shape_manual(values=c(18, 16, 17))+ 
  scale_color_manual(values=c("darkorange","darkcyan", "goldenrod3"))+
  xlim(5, 8)+
  ylim(1.5, 5)+
  geom_hline(yintercept=4, linetype="dotted", color="blue", size=2)+ #horizontal line at y=4
  geom_vline(xintercept=6, linetype="dashed", color="red", size=2) #vertical line at x=6

#add a linear regression line with "geom_smooth()" per species

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species, shape=Species))+
  geom_point(size=2)+
  scale_shape_manual(values=c(18, 16, 17))+ 
  scale_color_manual(values=c("darkorange","darkcyan", "goldenrod3"))+
  xlim(5, 8)+
  ylim(1.5, 5)+
  geom_smooth(method="lm", fullrange=T,se=F, size=2) #method "lm" indicate that you use a linear model to draw the regression line, fullrange indicates if you want to extend the line, se indicates if you want to draw the standard error around the line

###--------------------------------------------------###
### 4. the boxplot -------------------------------------
#the basic code
ggplot(iris, aes(x=Species, y=Sepal.Width))+
  geom_boxplot()

#a pretty way to present the point and the boxplot
ggplot(iris, aes(x=Species, y=Sepal.Width))+
  geom_boxplot()+
  geom_jitter(shape=16, position=position_jitter(0.1))#position_jitter will move the points from each other to avoid that the point overlap

#change the colors:
ggplot(iris, aes(x=Species, y=Sepal.Width,fill=Species))+ #"fill" changes the color inside the boxplot, "color" changes the color of the lines around the boxplot
  geom_boxplot()+
  geom_jitter(shape=16, position=position_jitter(0.1))+
  scale_fill_manual(values=c("darkorange","darkcyan", "goldenrod3")) #you have to use the argument "scale_fill_manual" because you want to change the color that fill the boxplot

#change the order of the species on the x scale
ggplot(iris, aes(x=Species, y=Sepal.Width,fill=Species))+
  geom_boxplot()+
  geom_jitter(shape=16, position=position_jitter(0.1))+
  scale_fill_manual(values=c("darkorange","darkcyan", "goldenrod3"))+
  scale_x_discrete(name="Species", limits=c("versicolor", "virginica", "setosa")) #indicates the name of the axis and the order of the variable in the axis


###--------------------------------------------------###
### 5. barplot -------------------------------------

#the basic plot without errorbar
ggplot(iris, aes(x=Species, y=Sepal.Length))+
  geom_bar(stat="identity")

#let's make it more fancy by changing the size of the bar and the colors
ggplot(iris, aes(x=Species, y=Sepal.Length, fill= Species))+
  geom_bar(stat="identity",width=0.5)+
  scale_fill_manual(values=c("darkorange","darkcyan", "goldenrod3"))

#add errorbar
#aggregate your data to calculate the mean and standard deviation per species
iris.mean<-aggregate(Sepal.Length ~ Species, data=iris, mean)#mean
iris.sd<-c(by(iris$Sepal.Length, iris$Species,sd)) #standard deviation
iris2<-cbind(iris.mean,iris.sd) #create a new dataframe with the mean and standard deviation per species
colnames(iris2)<-c("Species","mean","sd")#rename the columns, just to make it prettier

ggplot(iris2, aes(x=Species, y=mean,fill=Species))+
  geom_bar(stat="identity")+
  geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.2,
                position=position_dodge(.9),size=1)+
  scale_fill_manual(values=c("darkorange","darkcyan", "goldenrod3"))

#add some text
ggplot(iris2, aes(x=Species, y=mean, fill= Species))+
  geom_bar(stat="identity",width=0.5)+
  geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.2,
                position=position_dodge(.9),size=1)+
  scale_fill_manual(values=c("darkorange","darkcyan", "goldenrod3"))+
  geom_text(aes(label=mean), vjust=7, color="black", size=5) # vjust adjust the text in the plot, play around to find the best position

#the case of 2 factors of interest
#let's add a second factor : "tall" and "small"
iris2$size<-c("tall","tall","small")

ggplot(iris2, aes(x=size, y=mean, fill= Species))+
  geom_bar(stat="identity",width=0.5, position=position_dodge())+
  scale_fill_manual(values=c("darkorange","darkcyan", "goldenrod3"))

###--------------------------------------------------###
### 6. Upgrade your plot to the next level with the function theme() -------------------------------------

#add a title
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species, shape=Species))+
  geom_point(size=2)+
  scale_shape_manual(values=c(18, 16, 17))+ 
  scale_color_manual(values=c("darkorange","darkcyan", "goldenrod3"))+
  scale_x_continuous(name="Length of sepal (cm)", limits=c(5,8)) +
  scale_y_continuous(name="Width of sepal (cm)", limits=c(1.5,5))+
  geom_smooth(method="lm", fullrange=T,se=F)+
  labs(title="Width of Species (cm) in function of length of sepal (cm)") #add a title

#change legend position and legend title
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species, shape=Species))+
  geom_point(size=2)+
  scale_shape_manual(values=c(18, 16, 17))+ 
  scale_color_manual(values=c("darkorange","darkcyan", "goldenrod3"))+
  scale_x_continuous(name="Length of sepal (cm)", limits=c(5,8)) +
  scale_y_continuous(name="Width of sepal (cm)", limits=c(1.5,5))+
  geom_smooth(method="lm", fullrange=T,se=F)+
  labs(title="Width of Species (cm) in function of length of sepal (cm)",color="Species")+
  theme(legend.position = c(0.89,0.85), #use coordonate to change legend position
        legend.title = element_text(colour="black", size=10,face="bold")) #change the size, color and face of the title

#or

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species, shape=Species))+
  geom_point(size=2)+
  scale_shape_manual(values=c(18, 16, 17))+ 
  scale_color_manual(values=c("darkorange","darkcyan", "goldenrod3"))+
  scale_x_continuous(name="Length of sepal (cm)", limits=c(5,8)) +
  scale_y_continuous(name="Width of sepal (cm)", limits=c(1.5,5))+
  geom_smooth(method="lm", fullrange=T,se=F)+
  labs(title="Width of Species (cm) in function of length of sepal (cm)",color="Species")+
  theme(legend.position = "top", #move the legend to the top but it could also be " bottom", "right", "left" etc.
        legend.title = element_text(colour="black", size=10,face="bold"))

#change the background
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species, shape=Species))+
  geom_point(size=2)+
  scale_shape_manual(values=c(18, 16, 17))+ 
  scale_color_manual(values=c("darkorange","darkcyan", "goldenrod3"))+
  scale_x_continuous(name="Length of sepal (cm)", limits=c(5,8)) +
  scale_y_continuous(name="Width of sepal (cm)", limits=c(1.5,5))+
  geom_smooth(method="lm", fullrange=T,se=F)+
  labs(title="Width of Species (cm) in function of length of sepal (cm)",color="Species")+
  theme(legend.position = c(0.89,0.85),
        legend.title = element_text(colour="black", size=10,face="bold"),
        panel.background = element_rect(fill = "white", colour = "grey50")) #white background with grey line around the background


#or use a predefined background

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species, shape=Species))+
  geom_point(size=2)+
  scale_shape_manual(values=c(18, 16, 17))+ 
  scale_color_manual(values=c("darkorange","darkcyan", "goldenrod3"))+
  scale_x_continuous(name="Length of sepal (cm)", limits=c(5,8)) +
  scale_y_continuous(name="Width of sepal (cm)", limits=c(1.5,5))+
  geom_smooth(method="lm", fullrange=T,se=F)+
  labs(title="Width of Species (cm) in function of length of sepal (cm)",color="Species")+
  theme_classic() #it exists plenty of predefined background that you can find on internet


#change the axis

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species, shape=Species))+
  geom_point(size=2)+
  scale_shape_manual(values=c(18, 16, 17))+ 
  scale_color_manual(values=c("darkorange","darkcyan", "goldenrod3"))+
  scale_x_continuous(name="Length of sepal (cm)", limits=c(5,8)) +
  scale_y_continuous(name="Width of sepal (cm)", limits=c(1.5,5))+
  geom_smooth(method="lm", fullrange=T,se=F)+
  labs(title="Width of Species (cm) in function of length of sepal (cm)",color="Species")+
  theme(legend.position = c(0.89,0.85),
        legend.title = element_text(color="black", size=10,face="bold"),
        legend.text = element_text(color="black", size=8,face="bold"),
        legend.key = element_rect(fill = "white"),
        plot.title = element_text(color="red", size=14, face="bold"),
        panel.background = element_rect(fill = "white", colour = "grey50"),
        axis.title.y = element_text(color="blue", size=14, face="bold"), #change the color, size and face of the name of the axis y
        axis.text.y = element_text(face="bold", color="black", 
                                   size=20,angle=45), #change the size and angle of the number of the axis y
        axis.text.x = element_text(face="bold", color="black", 
                                   size=20,angle=45),
        axis.title.x = element_text(color="red", size=14, face="bold"))

#NB: to remove a title or axis use for example : "plot.title = element_blank()"

#divide the plot into panels with "facet_wrap"

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species, shape=Species))+
  geom_point(size=2)+
  scale_shape_manual(values=c(18, 16, 17))+ 
  scale_color_manual(values=c("darkorange","darkcyan", "goldenrod3"))+
  scale_x_continuous(name="Length of sepal (cm)", limits=c(5,8)) +
  scale_y_continuous(name="Width of sepal (cm)", limits=c(1.5,5))+
  geom_smooth(method="lm", fullrange=T,se=F)+
  labs(title="Width of Species (cm) in function of length of sepal (cm)",color="Species")+
  theme(legend.position = c(0.89,0.85),
        legend.title = element_text(color="black", size=10,face="bold"),
        legend.text = element_text(color="black", size=8,face="bold"),
        legend.key = element_rect(fill = "white"),
        plot.title = element_text(color="red", size=14, face="bold"),
        panel.background = element_rect(fill = "white", colour = "grey50"),
        axis.title.y = element_text(color="blue", size=14, face="bold"),
        axis.text.y = element_text(face="bold", color="black", 
                                   size=20,angle=45),
        axis.text.x = element_text(face="bold", color="black", 
                                   size=20,angle=45),
        axis.title.x = element_text(color="red", size=14, face="bold"))+
  facet_wrap(~ Species) #divide in function of the Species 
